<template>
    <div class="overview-page">
        <div class="title-box">
            <div class="title">
                <p>数据概览</p>
                <el-tooltip effect="dark" placement="bottom-start">
                    <template #content>
                        <p v-for="item in survey" :key="item">{{ item?.label }}：{{ item?.tip }}</p>
                    </template>
                    <el-icon class="box-icon">
                        <QuestionFilled />
                    </el-icon>
                </el-tooltip>
            </div>
        </div>
        <div class="container">
            <ZWSearch ref="searchRef" row-num="4" :option="searchOption" @search="search" @reset="reset" />

            <div class="data-box">
                <div v-for="(item, index) in survey" :key="index" class="data-item">
                    <div class="data-title">
                        <span>{{ item?.label }}</span>
                    </div>
                    <p class="num">{{ numFormat(peopleNum[item?.num]) }}<span v-if="item.ratio">%</span></p>
                </div>
            </div>
            <div class="title-block">
                <p>趋势图</p>
                <el-button @click="downLoadHandler">导出</el-button>
            </div>
            <div id="echarts" ref="myChartLineRef"></div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted, inject, nextTick } from 'vue';
import { numFormat, getDay } from '@/utils/utils';
import ZWSearch from '@/components/zw/search-form/SearchForm';
import {
    getWiseManList,
    trendChartsDetail,
    trendoverviewDetail,
    trendChartsDetailExport
} from '@/api/ecommerce/wiseManList';
import { deepCopy } from '@/utils/helper';
const belongOptionList = reactive([]);
const selectTime = ref();
const sourceVal = ref(null);
const searchRef = ref();

const searchOption = computed(() => {
    return [
        {
            label: '来源渠道',
            name: 'source',
            value: '0',
            type: 'select',
            placeholder: '全部',
            optionList: [
                { label: '全部', value: '0' },
                { label: '抖音达人', value: '21' },
                { label: '快手达人', value: '22' }
            ],
            async change(val: any, from: any) {
                from.belong_talent = '';
                params.belong_talent = '';
                sourceVal.value = val;
                const daren_channel_id = sourceVal.value || '0';
                if (sourceVal.value != 0 && !sourceVal.value) {
                    belongOptionList.splice(0, belongOptionList.length);
                    return;
                }
                const data: any = await getWiseManList({
                    daren_channel_id,
                    auth_status: [2, 3],
                    page: 1,
                    page_size: 999
                });
                belongOptionList.splice(0, belongOptionList.length, ...data.data);
            }
        },
        {
            label: '归属达人',
            name: 'belong_talent',
            value: '',
            type: 'select',
            alway: true,
            placeholder: '全部',
            optionList: belongOptionList,
            formatOption: (v: any) => ({
                label: v.daren_name,
                value: v.id
            })
        },
        {
            label: '筛选日期',
            name: 'time',
            value: [],
            default: [getDay(-7), getDay(-1, true)],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            calendarChange: (val: any) => {
                const [e] = val;
                selectTime.value = e;
            },
            disabledDate: (time: any) => {
                const con1 = new Date(selectTime.value).getTime() - 90 * 24 * 60 * 60 * 1000;
                const con2 = new Date(selectTime.value).getTime() + 90 * 24 * 60 * 60 * 1000;
                return time < con1 || time > con2 || time.getTime() > new Date().setHours(-1);
            }
        }
    ];
});
const myChartLineRef = ref(null);
const echarts: any = inject('ec');

const peopleNum = ref<any>({});

// 折线图参数及导出参数
const params = reactive({
    source: '0', //来源 0-全部 1-抖音
    belong_talent: '', //归属达人
    time: [getDay(-7), getDay(-1, true)]
});

// 概览数据
const survey = ref<unknown>([
    {
        label: '支付金额(元)',
        tip: '筛选时间内，支付成功的订单总金额，包含运费，支付后退款，支付金额不扣减。',
        num: 'pay_amount'
    },
    {
        label: '支付订单数',
        tip: '筛选时间内，支付成功的订单总数，支付后退款，支付订单数不扣减。',
        num: 'pay_order_num'
    },
    {
        label: '退款金额(元)',
        tip: '筛选时间内，成功退款的订单总金额，包括订单部分商品退款的金额。',
        num: 'refund_amount'
    },
    {
        label: '退款订单数',
        tip: '筛选时间内，成功退款的订单总数，包括部分商品退款订单。',
        num: 'refund_order_num'
    },
    {
        label: '退款率',
        tip: '筛选时间内，退款订单数/支付订单数。',
        ratio: true,
        num: 'refund_probability'
    }
]);

// 折线图数据
const Data = reactive({
    nameList: [],
    dateList: [],
    dataList: []
});

// 折线图配置项
const getEchartsLine = () => {
    const myChartLine = echarts?.init(myChartLineRef.value);

    const line_data: Array<any> = [];
    Data.nameList.forEach((x, idx) => {
        line_data.push({
            name: x,
            type: 'line',
            data: Data.dataList[idx],
            smooth: true,
            symbol: 'circle'
        });
    });
    const option = {
        color: [
            '#FF9228',
            '#2EB5E3',
            '#4AD983',
            '#FF724D',
            '#ED1F45',
            '#FFB323',
            '#4A7EE6',
            '#8C5FBC',
            '#30CBA8',
            '#FDD300',
            '#CE31CE',
            '#5AE2E0',
            '#668EFF'
        ],
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            x: 'center',
            y: 'bottom',
            bottom: '30%',
            padding: [0, 0, 10, 0],
            data: Data.nameList
        },
        grid: {
            top: '5%',
            left: 32,
            right: 40,
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: Data.dateList,
            boundaryGap: false,
            offset: 3
        },
        yAxis: {
            type: 'value',
            name: '',
            nameGap: 10, // y轴name与横纵坐标轴线的间距
            nameTextStyle: {
                padding: [0, 35, 10, 0] // 加上padding可以调整其位置
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#969696'
            },
            splitLine: {
                lineStyle: {
                    type: 'line',
                    color: '#e8e8e8' // 分割线颜色
                }
            }
        },
        series: line_data
    };
    myChartLine.setOption(option);
    window.addEventListener('resize', function () {
        if (myChartLine) {
            myChartLine.resize();
        }
    });
};

// 获取数据总览
const queryAmountData = async () => {
    const data = await trendoverviewDetail(params);
    peopleNum.value = data;
};

// 获取数据趋势数据
const queryChartData = async () => {
    const data = await trendChartsDetail(params);
    Data.nameList = data.nameList;
    Data.dataList = data.dataList;
    Data.dateList = data.dateList;
    nextTick(() => {
        getEchartsLine();
    });
};

// 数据导出下载
const downLoadHandler = async () => {
    const data = await trendChartsDetailExport(params);
    window.open(data.url);
};

const search = (v: any) => {
    params.source = v.source || '0';
    params.belong_talent = v.belong_talent;
    params.time = v.time?.length ? v.time : [getDay(-7), getDay(-1)];
    queryAmountData();
    queryChartData();
};
//初始化归属达人列表
const getBelongList = async () => {
    const data: any = await getWiseManList({
        daren_channel_id: '0',
        auth_status: [2, 3],
        page: 1,
        page_size: 999
    });
    belongOptionList.splice(0, belongOptionList.length, ...data.data);
};
const reset = (v: any) => {
    sourceVal.value = '0';
    params.source = v.source;
    params.belong_talent = '';
    params.time = v.time;
    getBelongList();
};
onMounted(() => {
    queryAmountData();
    queryChartData();
    getBelongList();
});
</script>

<style lang="scss" scoped>
.overview-page {
    background: #fff;
    border: 1px solid #eaeaea;
    font-family: PingFangSC-Medium, 'PingFang SC';

    .title-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 17px 24px;
        border-bottom: 1px solid #eaeaea;

        .title {
            display: flex;
            align-items: center;
            font-size: 16px;
            font-weight: 500;
            color: #33302d;

            :deep(.box-icon) {
                text-align: center;
                font-size: 16px;
                margin-left: 4px;
                color: #969696;
                background: #fff;
                border-radius: 50%;
            }
        }
    }

    .container {
        padding: 0 24px 20px;

        :deep(.zw-search-form) {
            background-color: #fff;
            padding: 17px 0;
        }

        .title-block {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 40px;

            p {
                font-size: 16px;
                font-weight: 500;
                color: #33302d;
                display: flex;
                align-items: center;

                &::before {
                    display: inline-block;
                    content: '';
                    width: 3px;
                    height: 16px;
                    margin-right: 6px;
                    background: #ff6b00;
                    border-radius: 2px;
                }
            }
        }

        #echarts {
            display: flex;
            justify-content: center;
            height: 400px;

            // margin-top: -55px;
        }

        .data-box {
            margin-bottom: 40px;
            display: grid;
            grid-template-columns: repeat(5, 1fr);

            // grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
            // grid-row-gap: 32px;
            align-items: center;

            .data-item {
                .data-title {
                    display: flex;
                    align-items: center;

                    span {
                        font-size: 14px;
                        font-family: PingFangSC-Regular, 'PingFang SC';
                        font-weight: 400;
                        color: #666;
                        line-height: 20px;
                    }
                }

                .num {
                    padding-top: 8px;
                    font-size: 30px;
                    font-family: HelveticaNeue-Medium, HelveticaNeue;
                    font-weight: 500;
                    color: #33302d;
                    line-height: 36px;
                }
            }
        }
    }
}
</style>
